<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
    <meta name="viewport"
          content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"/>
    <title>私信</title>
    <script src="/js/jquery/jquery.min.js"></script>
    <script src="/js/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
    <script src="/js/bootstrap-4.1.1-dist/js/jquery.bootstrap.min.js"></script>
    <link rel="stylesheet" href="/js/bootstrap-3.3.7-dist/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="/js/plugins/chat/chat.css"/>

    <script src="/js/plugins/chat/flexible.js"></script>
    <script src="/js/plugins/jrender/jrender.min.js"></script>
    <link rel="stylesheet" href="/js/plugins/dialog2/dialog.css">
    <script src="/js/plugins/dialog2/dialog.min.js"></script>
    <script src="/js/common.js"></script>
    <script src="/js/checkLogin.js"></script>
    <link rel="stylesheet" href="/css/font/css/font-awesome.min.css">
    <script type="text/javascript" src="/js/emoji_jQuery.min.js"></script>
    <script>
        $(function () {
            var websocket;
            var params = getParams();

            //点击头像前往个人页面
            $(".fa").prop("href", "/userProfiles.html?id=" + params.receiverId);

            console.log(params);
            if ('WebSocket' in window) {
                console.log("此浏览器支持websocket");
                websocket = new WebSocket("ws://127.0.0.1:8088/websocketDemo/" + user.id);
            } else if ('MozWebSocket' in window) {
                alert("此浏览器只支持MozWebSocket");
            } else {
                alert("此浏览器只支持SockJS");
            }
            websocket.onopen = function (evnt) {
                $("#tou").html("链接服务器成功!")
            };
            var receiverInfo;
            $.get(baseUrl + "/users/" + params.receiverId, function (data) {
                console.log(data);
                receiverInfo = data;
                $('.receiverName').html(data.nickName);
            });

            //页面进入时加载历史消息
            $.get(baseUrl + "/users/chatMessages", {senderId: user.id, receiverId: params.receiverId}, function (data) {
                console.log(data);
                $.each(data, function (index, ele) {
                    if(ele.content.indexOf('[')!=-1){
                        //解析emjio
                        ele.content = $.emojiParse({
                            content: ele.content,
                            emojis: [{path: 'static/images/emoji/', code: ',', type: 'emoji'}]
                        });
                    }



                    //通过结果中发送者的id判断哪个是当前用户,是当前用户,就显示在右边
                    if (ele.sender.id == user.id) {
                        $(".message").append('<div class="show">\n' +
                            '      <div class="time">' + ele.sendTime + '</div>\n' +
                            '      <div class="msg">\n' +
                            '        <img src="' + ele.sender.headImgUrl + '" width="40px" alt="" />\n' +
                            '        <p><i class="msg_input"></i>' + ele.content + '</p>\n' +
                            '      </div>\n' +
                            '    </div>');
                    } else {
                        $(".message").append('<div class="send">\n' +
                            '      <div class="time">' + ele.sendTime + '</div>\n' +
                            '      <div class="msg">\n' +
                            '        <img src="' + ele.sender.headImgUrl + '" width="40px" alt="" />\n' +
                            '        <p><i class="msg_input"></i>' + ele.content + '</p>\n' +
                            '      </div>\n' +
                            '    </div>');
                    }
                });
                end()
            })

            websocket.onmessage = function (evnt) {
                $(".message").append('<div class="send">\n' +
                    '      <div class="time">' + CurentTime(new Date()) + '</div>\n' +
                    '      <div class="msg">\n' +
                    '        <img src="' + receiverInfo.headImgUrl + '" width="40px" alt="" />\n' +
                    '        <p><i class="msg_input"></i>' + evnt.data + '</p>\n' +
                    '      </div>\n' +
                    '    </div>');
                console.log(evnt);
                end();
            };
            websocket.onerror = function (evnt) {
                websocket.close();
            };
            websocket.onclose = function (evnt) {
                websocket.close();
            };
            window.onbeforeunload = function () {
                websocket.close();
            };

            //输入时发送按钮变色
            $('.footer').on('keyup', 'input', function () {
                if ($(this).val().length > 0) {
                    $(this).next().css('background', '#114F8E').prop('disabled', true);

                } else {
                    $(this).next().css('background', '#ddd').prop('disabled', false);
                }
            })
            //当按下Enter键时,发送消息
            $(window).keydown(function (event) {
                switch (event.keyCode) {
                    case 13:
                        $('#sendBtn').click();
                        break;
                    // ...
                    // 不同的按键可以做不同的事情
                    // 不同的浏览器的keycode不同
                    // 更多详细信息:     http://unixpapa.com/js/key.html
                    // 常用keyCode： 空格 32   Enter 13   ESC 27
                }
            });

            $('#sendBtn').click(function () {
                //判断是否有输入内容
                var message = $("[name='message']").val();
                if (message == "") {
                    //如果没有信息,直接返回
                    $(document).dialog({
                        type: 'notice',
                        content: '<span class="info-text">内容不能为空</span>',
                        autoClose: 1000,
                        position: 'bottom'
                    });
                    return;
                }
                //发送消息
                sendSocket();
                //清空输入框
                $('#message').val('');
                //
                $("[name='message']").next().css('background', '#ddd').prop('disabled', false);
                end();
            });

            function sendSocket() {
                if (websocket != null) {
                    var message = $("input[name='message']").val();
                    websocket.send(message);
                    if(message.indexOf('[')!=-1){
                        //解析emjio
                        message = $.emojiParse({
                            content: message,
                            emojis: [{path: 'static/images/emoji/', code: ',', type: 'emoji'}]
                        });
                    }

                    $(".message").append('<div class="show">\n' +
                        '      <div class="time">' + CurentTime(new Date()) + '</div>\n' +
                        '      <div class="msg">\n' +
                        '        <img src="' + user.headImgUrl + '" width="40px" alt="" />\n' +
                        '        <p><i class="msg_input"></i>' + message + '</p>\n' +
                        '      </div>\n' +
                        '    </div>');

                    $.get(baseUrl + "/messages/user/" + user.id + "?receiverId=" + params.receiverId + "&message=" + message, function (data) {
                        console.log(data);
                    });

                } else {
                    alert('未与服务器链接.');
                }
            }

            $('.back').click(function () {
                websocket.close();
            })

        });


        //格式化时间
        function CurentTime(date) {
            var year = date.getFullYear();
            var month = date.getMonth() + 1;
            var day = date.getDate();
            var hh = date.getHours();
            var mm = date.getMinutes();
            var ss = date.getSeconds();
            var clock = year + "-";
            if (month < 10)
                clock += "0";
            clock += month + "-";
            if (day < 10)
                clock += "0";
            clock += day + " ";
            if (hh < 10)
                clock += "0";
            clock += hh + ":";
            if (mm < 10) clock += '0';
            clock += mm + ":";
            if (ss < 10) clock += '0';
            clock += ss;
            return clock;
        }

        //跳转到底部
        function end() {
            var c = window.document.body.scrollHeight;
            window.scroll(0, c);
        }

    </script>
</head>

<body>
<header class="header">
    <h5 class="tit receiverName">123</h5>
    <a class="back" href="javascript:history.go(-1);"></a>
    <div class="right receiverData glyphicon glyphicon-option-vertical">
        <span><a class="fa fa-user fa-2x" id="head" href=""></a></span>
    </div>
</header>

<div class="message">
    <!--<div class="send">
        <div class="time">05/22 06:30</div>
        <div class="msg">
            <img id="sendImg" width="40px" alt="" />
            <p><i class="msg_input"></i>你好</p>
        </div>
    </div>-->

    <!--<div class="show">
        <div class="time">05/22 06:30</div>
        <div class="msg">
            <img id="receiverImg" width="40px" alt="" />
            <p><i class="msg_input"></i>好</p>
        </div>
    </div>-->
</div>


<div id="test"></div>
<div class="footer">
    <img id="emoji" src="/img/xiaolian.png"/>
    <input type="text" name="message" id="message">
    <p id="sendBtn">发送</p>
</div>
<!--<script src="/js/plugins/chat/chat.js"></script>-->
<script>
    $.Lemoji({
        emojiInput: '#message',
        emojiBtn: '#emoji',
        position: 'RIGTHTOP',
        length: 6,
        emojis: {
            emoji: {path: 'static/images/emoji', code: ',', name: 'Emoji表情'}
        }
    });
    // $('#sendBtn').click(function () {
    //     var content = $('#input').val();
    //     content = $.emojiParse({
    //         content: content,
    //         emojis: [{type: 'qq', path: 'static/images/qq/', code: ':'}, {
    //             path: 'static/images/tieba/',
    //             code: ';',
    //             type: 'tieba'
    //         }, {path: 'static/images/emoji/', code: ',', type: 'emoji'}]
    //     });
    //     //判断是否有输入内容
    //     var content = $("[name='message']").val();
    //     if (content == "") {
    //         //如果没有信息,直接返回
    //         $(document).dialog({
    //             type: 'notice',
    //             content: '<span class="info-text">内容不能为空</span>',
    //             autoClose: 1000,
    //             position: 'bottom'
    //         });
    //         return;
    //     }
    //     //发送消息
    //     sendSocket();
    //     //清空输入框
    //     $('#message').val('');
    //     //
    //     $("[name='message']").next().css('background', '#ddd').prop('disabled', false);
    //     end();
    // });
</script>
</body>
</html>